# albumtagger_amarok by kunal kerkar (aka tsudot)
#
# simple script which fetches album tag and inserts in the ID3 metadata

__module_name__ = "albumtagger_amarok"
__module_version__ = "0.1" 

import urllib
import time
import commands
from ID3 import *
from xml.dom import minidom

basic_url = "http://ws.audioscrobbler.com/2.0/?"
method = "track.getinfo"
api_key = "1895a6ef7a8783052dc011f6ed747964"	

def isPlaying():
	return commands.getoutput('dcop amarok player isPlaying')

def countDown(seconds):
	sleep(seconds)

def getTrackDetails():
	global artist
	global track
	artist = commands.getoutput('dcop amarok player artist')
	track = commands.getoutput('dcop amarok player title')

def getAlbum():
	global artist
	global track
	global method
	global api_key
	global basic_url

	url = 'http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=1895a6ef7a8783052dc011f6ed747964&artist='+artist+'&track='+track
	feed = urllib.urlopen(url)
	xml = minidom.parse(feed)
	lfm = xml.childNodes[0]
	track = lfm.childNodes[1]
	album = track.childNodes[19]
	album_title = album.childNodes[3]
	album_title_data = album_title.firstChild.data
	putid3tag(album_title_data)

def putid3tag(album_title):
	if(album_title== 0):
		return 0
	else:
		path = commands.getoutput('dcop amarok player path')
		print "Album: "+album_title+ " has been appended to the track"
		id3info = ID3(path)
		id3info.album = album_title

def findTime():
	totalTime = commands.getoutput('dcop amarok player trackTotalTime')
	currentTime = commands.getoutput('dcop amarok player trackCurrentTime')
	leftTime = int(totalTime) - int(currentTime)
	print "Time left for the next check: "+leftTime
	return leftTime

if __name__ == "__main__":

	while True:
		if(isPlaying()):
			getTrackDetails()
			getAlbum()
			countDown(findTime())

		else:

			print "No tracks playing"
			countDown()

